import json, time
from datetime import datetime

from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.db.models import Q
from django.core.context_processors import csrf

from siberian.models import Blacklist, Contribution, Blocklist

def contribute(request):
    if 't' not in request.POST:
        raise ValueError

    methods = {'1' : __contribute_1, '2' : __contribute_2}

    t = request.POST['t']
    if t not in methods:
        raise ValueError

    return methods[t](request)

def __contribute_1(request):
    if 'n' not in request.POST:
        raise ValueError

    phone_number = request.POST['n']
    if len(phone_number) == 0:
        raise ValueError

    user_phone_number = request.POST['un'] if 'un' in request.POST else ''
    comment = request.POST['c'] if 'c' in request.POST else ''

    Contribution.objects.create(
            phone_number=phone_number,
            user_phone_number=user_phone_number,
            comment=comment,
            date_added=datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")).save() 

    return HttpResponse('OK')

def __contribute_2(request):
    if 'bn' not in request.POST:
        raise ValueError

    block_phone_number = request.POST['bn']
    if len(block_phone_number) == 0:
        raise ValueError

    if 'bt' not in request.POST:
        raise ValueError

    block_time = datetime.fromtimestamp(int(request.POST['bt'])).strftime("%Y-%m-%d %H:%M:%S")

    user_phone_number = request.POST['un'] if 'un' in request.POST else ''

    Blocklist.objects.create(
            user_phone_number=user_phone_number,
            block_phone_number=block_phone_number,
            block_time=block_time,
            date_added=datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")).save() 

    return HttpResponse('OK')

def show_contribute_form(request):
    c = {}
    c.update(csrf(request))
    return render_to_response('siberian/contribute.html', c)

def query(request):
    if 't' not in request.GET:
        raise ValueError

    t = request.GET['t']
    methods = {'1' : __query_1, '2' : __query_2}
    if t not in methods:
        raise ValueError

    return methods[t](request)

def __query_1(request):
    if 'n' not in request.GET:
        raise ValueError

    n = int(request.GET['n'])

    response = {}

    objects = Blacklist.objects.filter(phone_number=n)
    if len(objects) > 0:
        response_keys = {'i' : 'id', 'r' : 'region', 'sp' : 'service_providers', 'm' : 'message'}
        response = __make_simple_response_object(objects[0], response_keys)

    return HttpResponse(json.dumps(response), mimetype='application/json')

def __query_2(request):
    if 'v' not in request.GET:
        raise ValueError

    v = int(request.GET['v'])

    limit = 1
    response = {'m' : False, 'c' : 0, 'v' : []}

    objects = Blacklist.objects.filter(id__gt=v)
    if len(objects) <= 0:
        return HttpResponse(json.dumps(response), mimetype='application/json')

    entry = objects[0]
    new_items = Blacklist.objects.filter(Q(id__gte=entry.id) | Q(last_updated__gte=entry.last_updated))
    response_keys = {'i' : 'id', 'r' : 'region', 'sp' : 'service_providers', 'm' : 'message'}
    if len(new_items) > limit:
        response['m'] = True
        response['c'] = limit
        new_items = new_items[:limit]
    else:
        response['m'] = False
        response['c'] = len(new_items)

    values = []
    for o in new_items:
        values.append(__make_simple_response_object(o, response_keys))

    response['v'] = values

    return HttpResponse(json.dumps(response), mimetype='application/json')

def __make_simple_response_object(o, keys):
    r = {}
    for k, v in keys.items():
        r[k] = o.__getattribute__(v)

    return r
